package com.liumin.comlink.http.rx;


import com.liumin.comlink.http.exception.ExceptionHandle;

import org.reactivestreams.Publisher;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableTransformer;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 2019/12/25 15:02
 *
 * @author LiuWeiHao
 */
public class RxFlowableSchedulers {

    /**
     * 统一线程处理
     */
    public static <T> FlowableTransformer<T, T> rxSchedulerHelper() {    //compose简化线程
        return tFlowable -> tFlowable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }


    public static <T> FlowableTransformer<T, T> handleResult() {
        return upstream -> upstream.onErrorResumeNext(throwable -> {
            return Flowable.error(ExceptionHandle.handleException(throwable));
        });
    }

    /**
     * 服务其返回的数据解析
     * 正常服务器返回数据和服务器可能返回的exception
     *
     * @param <T>
     */
    private static class ResponseFunction<T> implements Function<T, ObservableSource<T>> {

        @Override
        public ObservableSource<T> apply(T tResponse) throws Exception {
//            int code = tResponse.code();
//            String message = tResponse.message();
//            if (200 == code) {
//                if (tResponse.body() != null) {
//                    return Observable.just(tResponse.body());
//                } else {
//                    return Observable.error(new ApiException(code, "Response body is null!"));
//                }
//            } else {
//                return Observable.error(new ApiException(code, message));
//            }
            return null;
        }
    }


    /**
     * 生成Flowable
     *
     * @param t baseresponse
     */
    public static <T> Flowable<T> createData(final T t) {
        return Flowable.create(emitter -> {
            try {
                emitter.onNext(t);
                emitter.onComplete();
            } catch (Exception e) {
                emitter.onError(e);
            }
        }, BackpressureStrategy.BUFFER);
    }


}
